package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.dto.FixDataJobDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ContactUserEntity;
import com.xbongbong.saas.domain.entity.CustomerUserEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.subform.ContactTeamEnum;
import com.xbongbong.saas.enums.subform.CustomerTeamEnum;
import com.xbongbong.saas.model.ContactUserModel;
import com.xbongbong.saas.model.CustomerUserModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.impl.CustomerModelImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

//import com.xbongbong.saas.enums.SelectProductBusinessEnum;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/8/29 14:18
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/job")
public class JobController {
    private static final Logger LOG = LoggerFactory.getLogger(JobController.class);

    @Resource
    private EsHelper esHelper;
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private ContactUserModel contactUserModel;
    @Resource
    private CustomerUserModel customerUserModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private CustomerModelImpl customerModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    @Resource
    private IndexTypeModel indexTypeModel;

    /**
     * 联系人团队修复
     * @param fixDataJobDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/fixContactTeam", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixContactTeam(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        for (String corpid : corpidList){
            Integer page = 0;
            List<PaasFormDataEntityExt> paasFormDataEntityExtList = new ArrayList<>();
            paasFormDataEntityExtList.add(new PaasFormDataEntityExt());
            while (!paasFormDataEntityExtList.isEmpty()) {
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                if (Objects.nonNull(fixDataJobDTO.getDataId())){
                    boolQueryBuilder.filter(termQuery("dataId",fixDataJobDTO.getDataId()));
                }
                boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CONTACT.getType()));
                SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTACT.getIndex());
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                sourceBuilder.query(boolQueryBuilder);
                searchRequest.source(sourceBuilder);
                page++;
                PageRequest pageRequest = EsUtil.setPage(sourceBuilder, page, 100);
                XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);
                paasFormDataEntityExtList = esEntities.getContent();
                if (paasFormDataEntityExtList.isEmpty()){
                    continue;
                }
                List<Long> contactIdList = new ArrayList<>();
                Set<Long> customerIdList = new HashSet<>();
                Map<Long,List<Long>> contactIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (PaasFormDataEntityExt entityExt : paasFormDataEntityExtList){
                    contactIdList.add(entityExt.getDataId());
                    Long customerId = entityExt.getData().getLong(ContactEnum.CUSTOMER_NAME.getAttr());
                    if (Objects.nonNull(customerId)){
                        customerIdList.add(customerId);
                    }
                    List<Long> idList = contactIdMap.getOrDefault(customerId,new ArrayList<>());
                    idList.add(entityExt.getDataId());
                    contactIdMap.put(customerId,idList);
                }
                boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                boolQueryBuilder.filter(termsQuery(ContactTeamEnum.getEsAttr(ContactTeamEnum.DATA_ID),contactIdList));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
                List<PaasFormDataEntity> contactUserEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTACT_TEAM,boolQueryBuilder,PaasFormDataEntity.class,Arrays.asList(ContactTeamEnum.getAttrConnectData(ContactTeamEnum.DATA_ID), ContactTeamEnum.getAttrConnectData(ContactTeamEnum.USER_ID)));
                List<ContactUserEntity> userTeamEntities1 = (List<ContactUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_CONTACT_TEAM, contactUserEntityList);
                Map<Long,List<String>> contactUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ContactUserEntity entity : userTeamEntities1){
                    List<String> userIdList = contactUserMap.getOrDefault(entity.getDataId(),new ArrayList<>());
                    userIdList.add(entity.getUserId());
                    contactUserMap.put(entity.getDataId(),userIdList);
                }

                List<ContactUserEntity> insertList = new ArrayList<>();
                if (!customerIdList.isEmpty()){
                    boolQueryBuilder = boolQuery();
                    boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                    boolQueryBuilder.filter(termsQuery(CustomerTeamEnum.getEsAttr(CustomerTeamEnum.DATA_ID),customerIdList));
                    boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
                    IndexTypeEnum customerTeamIndex = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
                    boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, customerTeamIndex.getType()));
                    List<PaasFormDataEntity> customerUserEntityList = esHelper.findByScroll(customerTeamIndex,boolQueryBuilder,PaasFormDataEntity.class,Arrays.asList(CustomerTeamEnum.getAttrConnectData(CustomerTeamEnum.DATA_ID), CustomerTeamEnum.getAttrConnectData(CustomerTeamEnum.USER_ID), CustomerTeamEnum.getAttrConnectData(CustomerTeamEnum.USER_NAME), CustomerTeamEnum.getAttrConnectData(CustomerTeamEnum.IS_MAIN)));
                    List<CustomerUserEntity> userTeamEntities = (List<CustomerUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(customerTeamIndex, customerUserEntityList);

                    for (CustomerUserEntity entity : userTeamEntities){
                        if (contactIdMap.containsKey(entity.getDataId())){
                            List<Long> idList = contactIdMap.get(entity.getDataId());
                            for (Long contactId : idList){
                                if (contactUserMap.containsKey(contactId)){
                                    List<String> userIdList = contactUserMap.get(contactId);
                                    if (!userIdList.contains(entity.getUserId())){
                                        ContactUserEntity contactUserEntity = new ContactUserEntity();
                                        contactUserEntity.setCorpid(corpid);
                                        contactUserEntity.setUserId(entity.getUserId());
                                        contactUserEntity.setUserName(entity.getUserName());
                                        contactUserEntity.setCustomerId(entity.getDataId());
                                        contactUserEntity.setDataId(contactId);
                                        contactUserEntity.setIsMain(entity.getIsMain());
                                        insertList.add(contactUserEntity);
                                    }
                                }
                            }
                        }
                    }
                }
                if (!insertList.isEmpty()){
                    contactUserModel.insertBatch(insertList, false);
                }
            }
        }
        return null;
    }

    @RequestMapping(value = "/fixCustomerTeam", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixCustomerTeam(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        for (String corpid : corpidList) {
            Integer page = 0;
            List<PaasFormDataEntityExt> paasFormDataEntityExtList = new ArrayList<>();
            paasFormDataEntityExtList.add(new PaasFormDataEntityExt());
            while (!paasFormDataEntityExtList.isEmpty()) {
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                boolQueryBuilder.filter(termQuery(CustomerManagementEnum.getEsAttr4Keyword(CustomerManagementEnum.IS_PUBLIC),0));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CUSTOMER.getType()));
                SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CUSTOMER.getIndex());
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                sourceBuilder.query(boolQueryBuilder);
                searchRequest.source(sourceBuilder);
                page++;
                PageRequest pageRequest = EsUtil.setPage(sourceBuilder, page, 100);
                XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);
                paasFormDataEntityExtList = esEntities.getContent();
                if (paasFormDataEntityExtList.isEmpty()) {
                    continue;
                }
                List<Long> customerIdList = new ArrayList<>();
                for (PaasFormDataEntityExt entityExt : paasFormDataEntityExtList){
                    customerIdList.add(entityExt.getDataId());
                }
                List<Long> hasTeamCustomerIdList = customerUserModel.getDataIdForTempJob(corpid,customerIdList);
                customerIdList.removeAll(hasTeamCustomerIdList);
                if (customerIdList.isEmpty()){
                    continue;
                }
                LOG.warn("fixCustomerTeam:" + JSONArray.toJSONString(customerIdList));
                List<CustomerUserEntity> insertList = new ArrayList<>();
                for (Long customerId : customerIdList){
                    CustomerUserEntity customerUserEntity = new CustomerUserEntity();
                    customerUserEntity.setCorpid(corpid);
                    customerUserEntity.setUserId("12653822631289754");
                    customerUserEntity.setUserName("黄瑞");
//                    customerUserEntity.setUserId("1");
//                    customerUserEntity.setUserName("张杰");
                    customerUserEntity.setDataId(customerId);
                    customerUserEntity.setIsMain(1);
                    customerUserEntity.setDistributionTime(0L);
                    customerUserEntity.setBackTime(0L);
                    customerUserEntity.setAddTime(DateTimeUtil.getInt());
                    customerUserEntity.setUpdateTime(DateTimeUtil.getInt());
                    customerUserEntity.setDel(0);
                    insertList.add(customerUserEntity);
                }
                if (!insertList.isEmpty()){
                    customerUserModel.insertBatch(insertList, false);
                }
            }
        }
        return null;
    }


    @RequestMapping(value = "/fixCombData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixCombData(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        List<String> corpidList = Collections.singletonList("ding19adedd0e8a1731135c2f4657eb6378f");
        String attr = "text_32";
        for (String corpid : corpidList) {
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByKey(65288,corpid);
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(),FieldAttrEntity.class);
            Map<String,String> itemMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (FieldAttrEntity entity : explainList){
                if (Objects.equals(entity.getAttr(),attr)){
                    for (ItemPoJo itemPoJo : entity.getItems()){
                        itemMap.put(itemPoJo.getText(),itemPoJo.getValue().toString());
                    }
                }
            }
            Integer page = 0;
            List<PaasFormDataEntityExt> paasFormDataEntityExtList = new ArrayList<>();
            paasFormDataEntityExtList.add(new PaasFormDataEntityExt());
            while (!paasFormDataEntityExtList.isEmpty()) {
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CUSTOMER.getType()));
                SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CUSTOMER.getIndex());
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                sourceBuilder.query(boolQueryBuilder);
                searchRequest.source(sourceBuilder);
                page++;
                PageRequest pageRequest = EsUtil.setPage(sourceBuilder, page, 100);
                XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);
                paasFormDataEntityExtList = esEntities.getContent();
                if (paasFormDataEntityExtList.isEmpty()) {
                    continue;
                }
                List<UpdateDataEntity> updateDataEntityList = new ArrayList<>();
                for (PaasFormDataEntityExt entityExt : paasFormDataEntityExtList){
                    String text32 = entityExt.getData().getString(attr);
                    if (itemMap.containsKey(text32)){
                        JSONObject json = new JSONObject();
                        json.put(attr,itemMap.get(text32));
                        updateDataEntityList.add(ExplainUtil.getUpdateData(entityExt.getDataId(),json,corpid));
                    }
                }
                LOG.warn("fixCombData:" + updateDataEntityList.size());
                if (!updateDataEntityList.isEmpty()){
                    customerModel.updateBatch(updateDataEntityList,corpid);
                }
            }
        }
        LOG.warn("fixCombData over");
        return null;
    }


}
